<template>
  <div class="bg-light">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/politics/ai" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">AI生成的练习题</h5>
      <button 
        class="regenerate-btn-small"
        @click="regenerateQuestion"
        :disabled="isRegenerating"
      >
        <i class="bi bi-arrow-clockwise"></i>
        {{ isRegenerating ? '生成中...' : '重新生成' }}
      </button>
    </div>

    <!-- 题目部分 -->
    <div v-if="currentQuestion" class="question-section">
      <div class="knowledge-point">
        <i class="bi bi-bookmark-fill"></i>
        题型：{{ currentQuestion.knowledgePoint }}
      </div>
      <div class="question-counter">
        <span>第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ totalQuestions }} 题</span>
        <span>已完成 {{ progressPercentage }}%</span>
      </div>
      <div class="question-progress">
        <div 
          class="question-progress-bar" 
          :style="{ width: progressPercentage + '%' }"
        ></div>
      </div>
      <div class="question">
        <p><strong>{{ currentQuestionIndex + 1 }}. {{ currentQuestion.text }}</strong></p>
        <!-- 单选题 -->
        <template v-if="currentQuestion.type === 26">
          <a 
            v-for="option in currentQuestion.options" 
            :key="option.key"
            href="#"
            class="option"
            :class="{ selected: selectedOption === option.key }"
            @click.prevent="selectOption(option.key)"
          >
            {{ option.key }}. {{ option.text }}
          </a>
        </template>
        <!-- 多选题 -->
        <template v-else-if="currentQuestion.type === 27">
          <a 
            v-for="option in currentQuestion.options" 
            :key="option.key"
            href="#"
            class="option"
            :class="{ selected: selectedOptions.includes(option.key) }"
            @click.prevent="toggleOption(option.key)"
          >
            {{ option.key }}. {{ option.text }}
          </a>
        </template>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div v-if="currentQuestion" class="bottom-tools position-fixed bottom-0 w-100 bg-white p-3">
      <div class="d-flex justify-content-between align-items-center">
        <div class="d-flex gap-2">
          <button 
            class="btn btn-outline-secondary btn-sm" 
            @click="prevQuestion"
            :disabled="currentQuestionIndex === 0"
          >
            上一题
          </button>
          <button 
            class="btn btn-outline-secondary btn-sm"
            @click="nextQuestion"
            :disabled="currentQuestionIndex === totalQuestions - 1"
          >
            下一题
          </button>
          <button
            class="btn btn-primary btn-sm submit-button"
            @click="submitAnswers(1)"
            :class="{ 'disabled-button': isSubmitted }"
            :disabled="isSubmitted"
          >
            结束答题
          </button>
        </div>
        <div class="d-flex gap-2">
          <router-link
            class="btn btn-primary btn-sm"
            @click="submitAnswers(2)"
            :to="`/politics/ai/explanation?year=${selectedYear}&question=${getSelectedQuestionValue()}&userAnswer=${getSelectedAnswerValue()}&examPaperId=${paperId}&currentQuestionIndex=${currentQuestionIndex}`"
            :disabled="isSubmitted"
          >
            <i class="bi bi-journal-text"></i>
            答案解析
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/router/http';
import router from "@/router/index";
export default {
  name: 'PoliticsAIPracticeView',
  data() {
    return {
      examPaperId: null,
      questionId: null,
      correctAnswer: null,
      currrentAnswer: null,
      selectedYear: 2024,
      currentQuestionIndex: 0,
      selectedOption: null,
      answerContentRecords: [], // 用于存储分析题答案内容
      userInputAnswer: {}, // 存储用户在富文本输入框中输入的答案
      userInputHistory: {}, // 用于存储每道题用户输入的历史记录（包含选项选择情况和输入框内容）
      totalQuestions: 0,
      isRegenerating: false,
      questions: [],
      currentQuestion: null,
      paperId: null,
      examPaper: null,
      selectedOptions: [], // 多选题的选项
      answeredQuestions: [], // 存储已答题目及答案
      startTime: 0, // 开始答题时间
      totalTimeSpent: 0, // 总答题时间
      isSubmitted: false, // 是否已提交答案
    }
  },
  async created() {
    this.paperId = this.$route.query.paperId;
    console.log('Paper ID from route:', this.paperId);
    if (!this.paperId) {
      console.error('No paper ID provided');
      this.$message?.error?.('未找到试卷ID');
      return;
    }

    try {
      this.currentQuestionIndex = Number(this.$route.query.currentQuestionIndex) || 0;
      await this.fetchExamPaper();

    } catch (error) {
      console.error('初始化失败:', error);
      this.$message?.error?.(error.message || '加载试卷失败');
    }
    this.startTime = Date.now();
  },
  computed: {
    progressPercentage() {
      return Math.round(((this.currentQuestionIndex + 1) / this.totalQuestions) * 100)
    }
  },
  methods: {
    getSelectedAnswerValue() {
      return this.currentQuestion.type === 26 ?
          this.selectedOption :
          this.selectedOptions.join(',');
    },
    getSelectedQuestionValue() {
      return this.questions[this.currentQuestionIndex].id;
    },
    async fetchExamPaper() {
      try {
        console.log('Fetching exam paper with ID:', this.paperId);
        const response = await http.post('/admin/examPaper/select/' + this.paperId, {
          paperId: this.paperId
        });
        
        if (response.data && response.data.code === 1) {
          this.examPaper = response.data.response;
          document.title = `${this.examPaper.name || 'AI生成的练习题'}`;
          
          // 处理试卷题目
          this.questions = [];
          this.examPaper.titleItems.forEach(titleItem => {
            titleItem.questionItems.forEach(question => {
              // 构建题目对象
              const formattedQuestion = {
                id: question.id,
                text: question.textContent.replace(/[\[\]\"]/g, ''), // 移除多余的 [] 和 "
                type: question.questionType,
                knowledgePoint: titleItem.name, // 使用题型作为知识点
                options: question.itemsAndIndex[0].items.map(item => ({
                  key: item.prefix,
                  text: item.content
                })),
                correct: question.correct,
                itemOrder: question.itemOrder
              };
              this.questions.push(formattedQuestion);
            });
          });
          
          // 按题目序号排序
          this.questions.sort((a, b) => a.itemOrder - b.itemOrder);
          
          // 设置初始题目
          if (this.questions.length > 0) {
            this.totalQuestions = this.questions.length;
            this.currentQuestion = this.questions[Number(this.$route.query.currentQuestionIndex) || 0];
          } else {
            throw new Error('试卷中没有题目');
          }
          
        } else {
          throw new Error('获取试卷详情失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取试卷详情失败:', error);
        this.$message?.error?.(error.message || '获取试卷详情失败');
        throw error;
      }
    },
    selectOption(key) {
      this.selectedOption = key;
      this.recordAnswer();
    },
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        const currentTime = Date.now();
        this.totalTimeSpent += currentTime - this.startTime;
        this.startTime = currentTime;
        
        this.currentQuestionIndex--;
        this.currentQuestion = this.questions[this.currentQuestionIndex];
        this.selectedOption = null;
        this.selectedOptions = [];
      }
    },
    nextQuestion() {
      if (this.currentQuestionIndex < this.totalQuestions - 1) {
        const currentTime = Date.now();
        this.totalTimeSpent += currentTime - this.startTime;
        this.startTime = currentTime;
        
        this.currentQuestionIndex++;
        this.currentQuestion = this.questions[this.currentQuestionIndex];
        this.selectedOption = null;
        this.selectedOptions = [];
      }
    },
    async regenerateQuestion() {
      this.isRegenerating = true
      try {
        const response = await http.post(`/student/ai/politics/practice/regenerate`, {
          paperId: this.paperId,
          questionIndex: this.currentQuestionIndex
        });
        
        if (response.data.success) {
          this.questions[this.currentQuestionIndex] = response.data.question;
          this.currentQuestion = response.data.question;
          this.selectedOption = null;
        }
      } catch (error) {
        console.error('重新生成题目失败:', error);
      } finally {
        this.isRegenerating = false;
      }
    },
    toggleOption(key) {
      const index = this.selectedOptions.indexOf(key);
      if (index === -1) {
        this.selectedOptions.push(key);
      } else {
        this.selectedOptions.splice(index, 1);
      }
      this.recordAnswer();
    },
    recordAnswer() {
      const currentAnswer = this.currentQuestion.type === 26 ? 
        this.selectedOption : 
        this.selectedOptions.join(',');
        
      const questionAnswerInfo = {
        questionId: this.currentQuestion.id,
        answer: currentAnswer
      };

      const existingIndex = this.answeredQuestions.findIndex(
        item => item.questionId === questionAnswerInfo.questionId
      );

      if (existingIndex > -1) {
        this.answeredQuestions[existingIndex] = questionAnswerInfo;
      } else {
        this.answeredQuestions.push(questionAnswerInfo);
      }
    },
    async submitAnswers(type) {
      const currentTime = Date.now();
      this.totalTimeSpent += currentTime - this.startTime;
      this.isSubmitted = true;

      try {
        const submitData = this.answeredQuestions.map(question => ({
          questionId: question.questionId,
          userAnswer: question.answer
        }));

        const submitInfo = {
          examPaperId: this.paperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 2, // 2 表示 AI 生成题目
          childDtos: submitData,
          thisTimeData: submitData
        };

        const response = await http.post('/student/answer/submitAnswerForPolitics', submitInfo);
        
        if (response.data.code === 1) {
          this.$message?.success?.('提交成功');
          if (type === 1) {
            this.$router.push('/politics/ai');
          }
        } else {
          throw new Error(response.data.message || '提交失败');
        }
      } catch (error) {
        console.error('提交答案失败:', error);
        this.$message?.error?.(error.message || '提交失败');
      }
    }
  }
}
</script>

<style scoped>
.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.regenerate-btn-small {
  background: #B19CD9;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.regenerate-btn-small:hover {
  background: #9f85c9;
}

.regenerate-btn-small:disabled {
  background: #ccc;
}

.question-section {
  background: white;
  margin: 15px;
  padding: 20px;
  border-radius: 15px;
}

.knowledge-point {
  color: #6c757d;
  font-size: 0.9rem;
  margin-bottom: 10px;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  display: inline-block;
}

.question-counter {
  color: #6c757d;
  font-size: 0.9rem;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-progress {
  height: 4px;
  margin: 8px 0;
  background-color: #e9ecef;
  border-radius: 2px;
}

.question-progress-bar {
  height: 100%;
  background-color: #B19CD9;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.option {
  display: block;
  padding: 12px 15px;
  margin: 10px 0;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  color: inherit;
  text-decoration: none;
}

.option.selected {
  background: #B19CD9;
  color: white;
  border-color: #B19CD9;
}

.bottom-tools {
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  padding: 20px;
  text-align: center;
}

.disabled-button {
  pointer-events: none;
  opacity: 0.5;
  background-color: #ccc !important;
  border-color: #ccc !important;
}

.submit-button {
  transition: all 0.3s ease;
}
</style> 